package st.business.tepth.business.user.busnumber.workholder.maintain.work.content.standardwork;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.CheckBox;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import st.business.tepth.R;
import st.business.tepth.R2;
import st.business.tepth.base.OnItemChooseListener;
import st.business.tepth.business.bean.CategoryBean;
import st.business.tepth.business.bean.MaintainWorkBean;
import st.business.tepth.business.bean.PersonBean;
import st.business.tepth.business.event.StartBrotherEvent;
import st.business.tepth.business.user.busnumber.workholder.maintain.work.content.standardwork.entity.Lv1;
import st.business.tepth.business.user.busnumber.workholder.maintain.work.content.standardwork.partrecord.PartRecordDelegate;
import st.business.tepth.business.user.busnumber.workholder.maintain.work.content.standardwork.workdetail.WorkDetailDelegate;
import st.business.tepth.manager.UserManager;
import st.shadow.library.core.base.mvp.MvpFragment;
import st.shadow.library.ui.dialog.DialogLoader;
import st.shadow.library.ui.dialog.IDialogClickListener;

/**
 * Author: shadow
 * Email:  1025431817@qq.com
 * Time:   2019-04-09 09:44
 * 保养标准项
 */

public class StandardWorkDelegate extends MvpFragment<StandardWorkPresenter> implements StandardWorkContract.View {
    public static StandardWorkDelegate newInstance(int repairId,
                                                   int repairTaskId,
                                                   ArrayList<CategoryBean> list,
                                                   String person,
                                                   int status) {
        Bundle bundle = new Bundle();
        bundle.putParcelableArrayList("list", list);
        bundle.putInt("status", status);
        bundle.putString("person", person);
        bundle.putInt("repairId", repairId);
        bundle.putInt("repairTaskId", repairTaskId);
        StandardWorkDelegate delegate = new StandardWorkDelegate();
        delegate.setArguments(bundle);
        return delegate;
    }

    @BindView(R2.id.recycler_view)
    RecyclerView mRecyclerView;
    @BindView(R2.id.cb_all)
    CheckBox mCbAll;
    private List<CategoryBean> mWorkBeans;
    private String person;
    private int mRepairId;
    private int mRepairTaskId;
    private int mStatus;
    private StandardWorkAdapter mAdapter;
    private DialogLoader mDialogLoader;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            mRepairId = bundle.getInt("repairId");
            mRepairTaskId = bundle.getInt("repairTaskId");
            mWorkBeans = bundle.getParcelableArrayList("list");
            mStatus = bundle.getInt("status");
            person = bundle.getString("person");
        }
    }

    public void resetData(int repairId, int repairTaskId,
                          ArrayList<CategoryBean> workBeans,
                          String person, int status) {
        mRepairId = repairId;
        mRepairTaskId = repairTaskId;
        mWorkBeans = workBeans;
        mStatus = status;
        this.person = person;
        if (mAdapter != null) {
            mAdapter.clearSelected();
            mAdapter.setNewData(StandardWorkAdapter.convertData(workBeans));
            if (mAdapter.getData().size() == 1) {
                mAdapter.expand(0);
            }
        }
        changeUiStatus();
    }

    @Override
    public StandardWorkPresenter getPresenter() {
        return new StandardWorkPresenter(this);
    }

    @Override
    public Object setLayout() {
        return R.layout.delegate_maintain_standard_work;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(_mActivity));
        RecyclerView.ItemAnimator itemAnimator = mRecyclerView.getItemAnimator();
        if (itemAnimator != null) {
            itemAnimator.setChangeDuration(0);
        }
        mRecyclerView.addOnItemTouchListener(new OnItemChildClickListener() {
            @Override
            public void onSimpleItemChildClick(BaseQuickAdapter baseQuickAdapter, View view, final int i) {
                Lv1 lv1 = (Lv1) baseQuickAdapter.getItem(i);
                if (lv1 != null) {
                    final MaintainWorkBean maintainWorkBean = lv1.getWorkBean();
                    if (maintainWorkBean != null) {
                        if (view.getId() == R.id.tv_content) {
                            if (i == 1) {
                                EventBus.getDefault().post(
                                        new StartBrotherEvent(PartRecordDelegate.
                                                newInstance(mRepairId, mRepairTaskId,
                                                        maintainWorkBean.getId(), mStatus)));
                            } else {
                                EventBus.getDefault().post(
                                        new StartBrotherEvent(WorkDetailDelegate.
                                                newInstance(mRepairId, mRepairTaskId,
                                                        maintainWorkBean.getId(), person, mStatus)));
                            }
                        } else if (view.getId() == R.id.tv_cancel_work) {
                            mDialogLoader.showWarning("取消打卡", "请确认", new IDialogClickListener() {
                                @Override
                                public void onClick() {
                                    mDialogLoader.changeToProgressType("正在提交...");
                                    mPresenter.cancelWork(UserManager.getInstance().getToken(),
                                            maintainWorkBean.getId(), i);
                                }
                            });
                        }
                    }
                }
            }
        });
        mDialogLoader = new DialogLoader(_mActivity);
        mRecyclerView.setAdapter(mAdapter =
                new StandardWorkAdapter(_mActivity,
                        StandardWorkAdapter.convertData(mWorkBeans),
                        new OnItemChooseListener<Boolean>() {
                            @Override
                            public void onChoose(Boolean aBoolean) {
                                mCbAll.setChecked(aBoolean);
                            }
                        }));
        if (mAdapter.getData().size() == 1) {
            mAdapter.expand(0);
        }
        changeUiStatus();
    }

    private void changeUiStatus() {
        mCbAll.setChecked(false);
        if (mStatus < 3) {
            mCbAll.setButtonDrawable(
                    _mActivity.getResources().getDrawable(R.drawable.selector_check_box));
        } else {
            mCbAll.setButtonDrawable(
                    _mActivity.getResources().getDrawable(android.R.color.transparent));
        }
    }


    @OnClick(R2.id.cb_all)
    public void onCbAll() {
        if (mAdapter != null) {
            mAdapter.checkAll(mCbAll.isChecked());
        }
    }

    public List<MaintainWorkBean> getSelectList() {
        if (mAdapter != null) {
            return mAdapter.getCheckList();
        }
        return null;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }


    @Override
    public void showCancelSucceed(final int position) {
        mDialogLoader.stopProgressWithSuccess("取消成功", "请确认", new IDialogClickListener() {
            @Override
            public void onClick() {
                if (mAdapter != null) {
                    MultiItemEntity entity = mAdapter.getItem(position);
                    if (entity != null) {
                        MaintainWorkBean maintainWorkBean = ((Lv1) entity).getWorkBean();
                        if (maintainWorkBean != null) {
                            if (deleteMe(maintainWorkBean.getUserList())) {
                                mAdapter.notifyItemChanged(position);
                            }
                        }
                    }

                }
                mDialogLoader.clearDialog();
            }

            private boolean deleteMe(List<PersonBean> list) {
                if (list != null) {
                    int position = -1;
                    for (int i = 0; i < list.size(); i++) {
                        if (list.get(i).getJob_no().equals(UserManager.getInstance()
                                .getCurrentUserCode())) {
                            position = i;
                            break;
                        }
                    }
                    if (position != -1) {
                        list.remove(position);
                        return true;
                    }
                }
                return false;
            }
        });

    }

    public int getConfirmCount() {
        if (mAdapter != null) {
            return mAdapter.getConfirmCount();
        }
        return -1;
    }

    @Override
    public void showError(String msg) {
        mDialogLoader.stopProgressWithFailed(msg, msg);
    }
}